// pages/member/cart/index.js
var t = getApp(),
  a = t.requirejs("check"),
  e = t.requirejs("core");
Page({
  data: {
    route: "member_cart",
    menu: t.tabBar,
    menu_show: false,
    icons: t.requirejs("icons"),
    show: false,
    edit_list: [],
    list: [],
    edit: false, //默认结算页面
    display: false,
    // editcheckall:!1
    merch_list: !1,
    ischeckall: true,
    member_change: true,
    delBtnWidth: 160, //删除按钮宽度单位（rpx）
    config: t.config,
    order_id:[],
    total: 0,
    management:0
  },
  //底部导航跳转
  menu_url: function(k) {
    e.menu_url(k, 2);
  },

  onGotUserInfo: function (q) {
    var that = this,
        cache = t.getCache("userinfo");

    // if (cache) {
    //     return;
    // }
    t.getUserInfo(q.detail.userInfo, function (t) {
      if (t != 1000) {
        var ucache = getApp().getCache("userinfo");
        if (ucache) {
          that.setData({
            display: false
          })
        }
      } else {
        that.setData({
          display: true
        })
      }
    }, q.detail.encryptedData, q.detail.iv);
  },

  // 授权获取用户信息判断
  authCheck: function () {
    var cache = getApp().getCache("userinfo");
    if (!cache.nickName && !cache.avatarUrl) {
      this.setData({
        display: true
      })
      return false;
    } else {
      this.setData({
        display: false
      })
      return true;
    }
  },

  // 取消登录
  cancel_auth: function () {
    this.setData({
      display: false
    })
  },

  /**
   * 购物车
   */
  onLoad: function(options) {
    var that = this;
    if (options != null && options != undefined) {
      that.setData({
        tabbar_index: options.tabbar_index ? options.tabbar_index : -1
      });
    }

    e.setting();
    // 页面初始化 options为页面跳转所带来的参数
    that.initEleWidth();
    // this.get_cart();
    that.setData({
      menu: getApp().tabBar,
      config: getApp().config
    })
    var key = t.isInArray(getApp().tabBar.list, that.data.route);
    if (options.key && options.key == 1 && key) {
      that.setData({
        tabbar_index: key,
        showtabbar: getApp().tabBar.IsDiDis ? getApp().tabBar.IsDiDis : false,
      })
    }
    if (that.data.tabbar_index >= 0) {
      that.setData({
        showtabbar: getApp().tabBar.IsDiDis ? getApp().tabBar.IsDiDis : false,
      })
    }
  },

  /**
   * 清空购物车
   */
  clearCart: function() {
    var that = this;
      that.setData({
        edit: !that.data.edit
      })
    
    
    // e.get("Cart/DelAllCart", {
    //   uid: t.getCache("userinfo").uid
    // }, function(res) {
    //   if (res.code == 0) {
    //     that.get_cart()
    //   } else {
    //     e.alert(res.msg)
    //   }
    // });
  },
	
  /**
   * 滑动删除页面效果
   */
  touchS: function(e) {
    if (e.touches.length == 1) {
      this.setData({
        //设置触摸起始点水平方向位置
        startX: e.touches[0].clientX
      });
    }
  },
  touchM: function(e) {
    if (e.touches.length == 1) {
      //手指移动时水平方向位置
      var moveX = e.touches[0].clientX;
      //手指起始点位置与移动期间的差值
      var disX = this.data.startX - moveX;
      var delBtnWidth = this.data.delBtnWidth;
      var txtStyle = "";
      if (disX == 0 || disX < 0) { //如果移动距离小于等于0，文本层位置不变
        txtStyle = "left:0px";
      } else if (disX > 0) { //移动距离大于0，文本层left值等于手指移动距离
        txtStyle = "left:-" + disX + "px";
        if (disX >= delBtnWidth) {
          //控制手指移动距离最大值为删除按钮的宽度
          txtStyle = "left:-" + delBtnWidth + "px";
        }
      }
      //获取手指触摸的是哪一项
      var index = e.currentTarget.dataset.index;
      var list = this.data.list;
      list[index].txtStyle = txtStyle;
      //更新列表的状态
      this.setData({
        list: list
      });
    }
  },
  touchE: function(e) {
    if (e.changedTouches.length == 1) {
      //手指移动结束后水平位置
      var endX = e.changedTouches[0].clientX;
      //触摸开始与结束，手指移动的距离
      var disX = this.data.startX - endX;
      var delBtnWidth = this.data.delBtnWidth;
      //如果距离小于删除按钮的1/2，不显示删除按钮
      var txtStyle = disX > delBtnWidth / 2 ? "left:-" + delBtnWidth + "px" : "left:0px";
      //获取手指触摸的是哪一项
      var index = e.currentTarget.dataset.index;
      var list = this.data.list;
      list[index].txtStyle = txtStyle;
      //更新列表的状态
      this.setData({
        list: list
      });
    }
  },
  //获取元素自适应后的实际宽度
  getEleWidth: function(w) {
    var real = 0;
    try {
      var res = wx.getSystemInfoSync().windowWidth;
      var scale = (750 / 2) / (w / 2); //以宽度750px设计稿做宽度的自适应
      // console.log(scale);
      real = Math.floor(res / scale);
      return real;
    } catch (e) {
      return false;
      // Do something when catch error
    }
  },
  initEleWidth: function() {
    var delBtnWidth = this.getEleWidth(this.data.delBtnWidth);
    this.setData({
      delBtnWidth: delBtnWidth
    });
  },
  //点击删除按钮事件
  delItem: function(i) {

    var that = this,
      cart_id = e.data(i).id; //获取列表中要删除项的cart_id
    e.confirm("是否确认删除该商品?", function() {
      e.get("Cart/DelCart", {
        cart_id: cart_id
      }, function(t) {

        0 == t.code ? (
          e.success('删除成功'),
          setTimeout(function() {
            that.setData({
                edit: false
              }),
              that.get_cart()
          }, 1e3)

        ) : (e.alert(t.msg))


      });
    })

  },
  onShow: function() {
    this.get_cart()
  },
  /**
   * 下拉刷新
   */
  onPullDownRefresh: function() {
    this.get_cart()
    wx.stopPullDownRefresh();
  },
  /**
   * 购物车列表
   * @param uid 用户id
   * @return array
   */
  get_cart: function() {
    var a,
      s = {},
      i = this;
    e.get("Cart/cart", {
      uid: getApp().getCache("userinfo").uid
    }, function(e) {
      e.info.forEach(function(t) {
        t.txtStyle = ""
      })
      if (e.info.length == 0) {
        i.setData({
          empty: 1
        })
      } else {
        i.setData({
          empty: !1
        })
      }
      var ischeckall=false;
      if (i.data.order_id.length < e.info.length){
        //每个商品默认选中
        for (var c in e.info) {
          if (i.data.order_id.indexOf(e.info[c].cart_id) > -1) {
            s[e.info[c].cart_id] = true
          } else {
            s[e.info[c].cart_id] = false
          }
        }
      }else{
        for (var c in e.info) {
          s[e.info[c].cart_id] = true
        }
        ischeckall=true;
      }
      //每个商品默认选中
      for (var c in e.info) {
        if (i.data.order_id.indexOf(e.info[c].cart_id)>-1){
          s[e.info[c].cart_id] = true
        }else{
          s[e.info[c].cart_id] = false
        }
      }
      a = {
          show: true, //隐藏loading
          checkObj: s, //每个商品默认选中状态
        ischeckall: ischeckall, //全选
          list: e.info || [],
          checkNum: e.info.length
        },
        i.setData(a)
      i.caculate()
    }, true)
  },
  /**
   *计算购物车商品总数量，总金额
   * @param this.data.list
   * @return string
   */

  caculate: function() {
    var t = this,
      order_money = 0,
      total = 0,
      s = t.data.checkObj,
      d = t.data.list;

    d.forEach(function(a) {
      if (s[a.cart_id] && a.sku) {
        total += parseFloat(a.num);
        order_money += parseFloat(a.num * a.sku.price);
      }
    })

    t.setData({
      order_money: order_money.toFixed(2),
      total: parseFloat(total)
    })
  },

  /**
   *购物车单个商品加减数量
   * @param cart_id
   * @param num 数量改变值
   * @return array
   */
  number: function(t) {
    // console.log(t, "528")
    var a = this,
      s = e.pdata(t),
      x = {},
      num = parseInt(s.value),
      o = s.id;
    console.log(num, "552")
    console.log(s, "852")
    if (!t.target.dataset.action) {
      console.log(11)
      return false;
    }

    if (t.target.dataset.action == "minus") {
      if (num <= 1) {
        return false;
      }
      num = num - 1;
    }
    if (t.target.dataset.action == "plus") {
      if (s.price == 0) {
        e.toast('限购数量为1')
        return false;
      }
      if (num >= s.min && s.min!=0) {
        e.toast('最大购买量 ' + s.min + '件！')
        return false;
      }
      num = num + 1;
    }
    e.post("Cart/cartNum", {
      cart_id: o,
      num: num, //购买数量
    }, function(t) {
      console.log(t, "阿羡")
      if (t.code == 0) {
        a.get_cart()
      }
      console.log(t, "阿离")
    })
  },

  /**
   *购物车商品全选
   * @param ischeckall
   * @return bool
   */
  checkAllClick: function(t) {
    var t = !this.data.ischeckall,
      e = this.data.checkObj,
      order_id_arr = [],
      a = {
        ischeckall: t,
        checkObj: e
      };
    console.log(t, "蓝忘机！")
    console.log(e, "魏无羡！！")
    console.log(a, '江厌离！！！')
    for (var i in e){
      if (t) {
        order_id_arr.push(i);
      } else {
        var index = order_id_arr.indexOf(i);
        order_id_arr.splice(index, 1);
      }
      a.checkObj[i] = t;
    }
    this.setData({
      order_id: order_id_arr
    })
    a.checkNum = t ? this.data.list.length : 0,
      this.setData(a)
    this.caculate()
  },

  /**
   *购物车单个商品选择
   * @param goodsid
   * @param checkObj bool值
   * @return bool
   */
  itemClick: function(t) {
    var a = this,
      i = e.pdata(t).id,
      s = e.pdata(t).goodsid,
      c = a.data.checkObj,
      l = a.data.checkNum,
      order_id_arr = a.data.order_id;

    if (c[i]){
      c[i] = false;l--;
      var index = order_id_arr.indexOf(i);
      order_id_arr.splice(index, 1);
    }else{
      order_id_arr.push(i);
      c[i] = true;
      l++;
    }
    //c[i] ? (c[i] = false, l--) : (c[i] = true, l++);
    var o = true;
    for (var n in c)
      if (!c[n]) {
        o = false;
        break
      } //有一个未选中，则为非全选状态
    console.log(c, 'aaaa')
    console.log(o, 'bbb')
    a.setData({
      checkObj: c,
      ischeckall: o,
      checkNum: l,
      order_id: order_id_arr
    })
    a.caculate()
  },

  /**
   *购物车修改，删除,支付
   */
  edit: function(t) {
    var i,
      s = e.data(t),
      that = this;
    switch (s.action) {
      //修改
      case "edit":
        this.setData({
          edit: true
        });
        break;
        //完成
      case "complete":
        this.setData({
          edit: false
        });
        break;
        //移动到关注
      case "move":
        var s = that.data.checkObj,
          l = [];
        for (var c in s)
          s[c] && l.push(c); //push() 方法可把它的参数顺序添加到 arrayObject 的尾部
        if (l.length < 1)
          return;
        l = l.toString() 
        e.post("member/cart/tofavorite", {
          ids: l
        }, function(t) {
          that.get_cart()
        });
        break;
        //删除
      case "delete":
        var s = that.data.checkObj,
          l = [];
        for (var c in s)
          s[c] && l.push(c); //push() 方法可把它的参数顺序添加到 arrayObject 的尾部
        if (l.length < 1)
          return;
        l = l.toString()
        e.confirm("是否确认删除该商品?", function() {
          e.post("Cart/DelCart", {
            cart_id: l
          }, function(t) {

            0 == t.code ? (
              e.toast('删除成功'),
              that.setData({
                edit: false
              }),
              that.get_cart()
            ) : e.alert(t.msg)


          });
        })
        break;
        //购买
      case "pay":
        var auth_res = that.authCheck();
        if (!auth_res) {
          return;
        }
        var s = that.data.checkObj,
          d = that.data.list,
          l = [],
          k = [];
        d.forEach(function(a) {
          if (s[a.cart_id] && a.sku) {
            l.push(a.cart_id)
          }
        })
        //push() 方法可把它的参数顺序添加到 arrayObject 的尾部
        if (l.length < 1)
          return;
        l = l.toString()
        wx.navigateTo({
          url: "/yb_mingpian/pages/order/create/index?cart_id=" + l + "&uid=" + getApp().getCache("userinfo").uid + "&type=cart"
        })
    }
  },

  //分享
  // onShareAppMessage: function() {
  //   return e.onShareAppMessage()
  // }
})